package com.zjitc.service.imp;

import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.zjitc.dao.OrderDao;
import com.zjitc.dao.OrderItemDao;
import com.zjitc.dao.ProductDao;
import com.zjitc.model.*;
import com.zjitc.service.CarService;
import com.zjitc.service.OrderService;
import com.zjitc.service.ShippingService;
import com.zjitc.utils.Paging;
import com.zjitc.utils.Utils;
import com.zjitc.utils.rabbit.RabbitMessage;

import java.util.ArrayList;
import java.util.Date;
import javax.servlet.http.HttpSession;

import com.zjitc.utils.redis.MyRedis;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * Create by IntelliJ IDEA
 *
 * @author: lhl
 * @date-Time: 2018/4/6 0006
 * @description:
 */
@Service
public class OrderServiceImpl implements OrderService {
    private static Logger logger = Logger.getLogger(OrderServiceImpl.class);
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderItemDao orderItemDao;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private RabbitMessage message;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CarService carService;
    @Autowired
    private MyRedis redis;
    @Autowired
    private ShippingService shippingService;

    @Override
    public void add(Order order) {
        Shipping shipping = shippingService.findOne(order.getUid());
        order.setName(shipping.getShippingName());
        order.setTelephone(shipping.getShippingTelephone());
        order.setAddress(shipping.getShippingAddress());
        orderDao.add(order);
        Gson gson = new Gson();
        redis.addCathc("orders", order.getOid(), gson.toJson(order));
        for (OrderItem item : order.getOrderItems()) {
            orderItemDao.add(item);
            redis.addCathc("orderItems", item.getItemId(), gson.toJson(item));
        }
    }

    @Override
    public void carToOrder(HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<CarItem> carItems = carService.findAll(user.getUid());
        Order order = new Order();
        order.setOid(Utils.getUUID());
        order.setOrderTime(new Date());
        order.setState(0);
        order.setName(user.getName());
        order.setTelephone(user.getTelephone());
        order.setUid(user.getUid());
        List<OrderItem> orderItems = new ArrayList<>();
        /**
         * 将购物车中的内容导入到OrderItems中再添加到数据库
         */
        double totalprice = 0;
        for (CarItem item : carItems) {
            OrderItem orderItem = new OrderItem();
            orderItem.setItemId(Utils.getUUID());
            orderItem.setCount(item.getCount());
            orderItem.setSubTotal(item.getPrice());
            orderItem.setPid(item.getProduct().getPid());
            orderItem.setOid(order.getOid());
            orderItem.setProduct(item.getProduct());
            orderItems.add(orderItem);

            totalprice += orderItem.getSubTotal();
        }
        order.setOrderItems(orderItems);
        order.setTotal(totalprice);
        orderService.add(order);
        carService.clear(user.getUid());
    }

    public void sortAdd(String uid, List<Order> list) {
        Gson gson = new Gson();
        if (list != null && uid != null) {
            for (Order order : list) {
                if (uid.equals(order.getUid())) {
                    redis.zadd(uid + "order", order.getOrderTime().getTime(), gson.toJson(order));
                }
            }
        }

    }

    @Override
    public Page<Order> findByUid(String uid, int pageIndex, int count) {
        redis.del(uid + "order");
        List<Order> orders = redis.allOrders();
        if (orders != null && !"".equals(orders)) {
            if (orders.size() != 0) {
                sortAdd(uid, orders);
                String name = uid + "order";
                Long aCatch = redis.zcard(name);
                int totalCount = aCatch.intValue();
                int pageCount = (int) Math.ceil(totalCount / count);
                Set<String> set = redis.zrange(name, count * pageIndex, count * pageIndex + count - 1);
                List<Order> temOrders = new ArrayList<Order>();
                Gson gson = new Gson();
                for (String str : set) {
                    Order order = gson.fromJson(str, Order.class);
                    List<OrderItem> items = redis.allItems();
                    List<OrderItem> itemList = new ArrayList<>();
                    if (items != null && !"".equals(items)) {
                        if (items.size() != 0) {
                            for (OrderItem orderItem : items) {
                                if (order.getOid().equals(orderItem.getOid())) {
                                    List<Product> products = redis.allProducts();
                                    if (products != null && !"".equals(products)) {
                                        if (products.size() != 0) {
                                            for (Product product : products) {
                                                if (orderItem.getPid().equals(product.getPid())) {
                                                    orderItem.setProduct(product);
                                                    itemList.add(orderItem);
                                                }
                                            }
                                        } else {
                                            Product product = productDao.findByPid(orderItem.getPid());
                                            orderItem.setProduct(product);
                                            itemList.add(orderItem);
                                        }
                                    }
                                }
                            }
                        } else {
                            List<OrderItem> orderItems = orderItemDao.findByOid(order.getOid());
                            for (OrderItem item : orderItems) {
                                Product product = productDao.findByPid(item.getPid());
                                item.setProduct(product);
                                itemList.add(item);
                            }
                        }
                    }
                    order.setOrderItems(itemList);
                    temOrders.add(order);
                }
                Paging<Order> paging = new Paging<>();
                Page page = paging.getPage(pageIndex, pageCount, temOrders);
                return page;
            }
        }
        logger.debug("redis服务出现问题，请维修人员尽快处理");
        int sqlCount = orderDao.count(uid);
        int pageCount = (int) Math.ceil(sqlCount / count);
        List<Order> orderList = orderDao.findLimitByUid(uid, pageIndex * count, count);
        for (int i = 0; i < orderList.size(); i++) {
            Order o = orderList.get(i);
            List<OrderItem> orderItems = orderItemDao.findByOid(o.getOid());
            for (int j = 0; j < orderItems.size(); j++) {
                OrderItem item = orderItems.get(j);
                // 3. 通过orderItem中的pid，查询商品信息
                Product pd = productDao.findByPid(item.getPid());
                item.setProduct(pd);
            }
            o.setOrderItems(orderItems);
        }
        Paging<Order> paging = new Paging<>();
        Page page = paging.getPage(pageIndex, pageCount, orderList);
        return page;
    }

    @Override
    public void deleteByOid(String oid) {
        orderItemDao.deleteByOid(oid);
        orderDao.deleteByOid(oid);
        List<OrderItem> items = redis.allItems();
        if (items != null && !"".equals(items)) {
            if (items.size() != 0) {
                for (OrderItem item : items) {
                    if (item.getOid().equals(oid)) {
                        redis.deleteById("orderItems", item.getItemId());
                    }
                }
                redis.deleteById("orders", oid);
            }
        }
    }

    @Override
    public List<Order> findOrders(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Order> orders = orderDao.findOrders();
        return orders;
    }

    @Override
    public List<OrderItem> findOrderItemsByOid(String oid) {
        Gson gson = new Gson();
        List<OrderItem> orderItemList = redis.allItems();
        if (orderItemList != null && !"".equals(orderItemList)) {
            if (orderItemList.size() != 0) {
                List<OrderItem> list = new ArrayList<>();
                for (OrderItem orderItem : orderItemList) {
                    if (oid.equals(orderItem.getOid())) {
                        String one = redis.getOneById("products", orderItem.getPid());
                        if (one != null && !"".equals(one)) {
                            Product product = gson.fromJson(one, Product.class);
                            orderItem.setProduct(product);
                            list.add(orderItem);
                        } else {
                            Product product = productDao.findByPid(orderItem.getPid());
                            orderItem.setProduct(product);
                            list.add(orderItem);
                        }
                    }
                }
                return list;
            }
        }
        logger.debug("redis服务出现问题，请维修人员尽快处理");
        List<OrderItem> items = orderItemDao.findByOid(oid);
        for (int j = 0; j < items.size(); j++) {
            OrderItem item = items.get(j);
            // 通过orderItem中的pid，查询商品信息,把商品添加进去
            Product pd = productDao.findByPid(item.getPid());
            item.setProduct(pd);
        }
        return items;
    }

    @Override
    public Order findBuyerByOid(String oid) {
        Order order = orderDao.findOrderByOid(oid);
        return order;
    }

    @Override
    public Order findOrderByOid(String oid) {
        String s = redis.getOneById("orders", oid);
        if (s != null && !"".equals(s)) {
            Gson gson = new Gson();
            Order order = gson.fromJson(s, Order.class);
            List<OrderItem> items = findOrderItemsByOid(oid);
            order.setOrderItems(items);
            return order;
        } else {
            logger.debug("redis服务出现问题，请及时处理");
            Order order = orderDao.findOrderByOid(oid);
            List<OrderItem> items = findOrderItemsByOid(oid);
            order.setOrderItems(items);
            return order;
        }
    }

    @Override
    public void update(Order order) {
        orderDao.update(order);
        Gson gson = new Gson();
        String s = gson.toJson(order);
        redis.alertById("orders", order.getOid(), s);
    }

    @Override
    public void updateOrderState(String oid) {
        /**
         * 应该在这个地方更改商品的数量
         */
        Order order = orderDao.findOrderByOid(oid);
        List<OrderItem> orderItems = order.getOrderItems();
        if (orderItems != null) {
            for (OrderItem orderItem : orderItems) {
                String pid = orderItem.getPid();
                Product product = productDao.findByPid(pid);
                product.setProductCount(product.getProductCount() - orderItem.getCount());
                productDao.update(product);
                Gson gson = new Gson();
                String s = gson.toJson(product);
                redis.alertById("products", pid, s);
            }
        }
        if (order.getState() == 0) {
            order.setState(1);
            Gson gson = new Gson();
            String s = gson.toJson(order);
            redis.alertById("orders", oid, s);
            orderDao.update(order);
        }
        /**
         * 订单状态：-1  ：退款
         *            0  ：未付款
         *            1  ：已经付款
         */
        System.out.println("更改订单的状态" + oid);
        System.out.println("订单此时的状态" + order.getState());
    }

    @Override
    public Order sckSkillRabbit(String pid, int count, HttpSession session) {
        Product product = productDao.findByPid(pid);
        if (count > product.getSkillCount()) {
            count = product.getSkillCount();
        }
        User user = (User) session.getAttribute("user");
        Order order = new Order();
        order.setOid(Utils.getUUID());
        order.setOrderTime(new Date());
        order.setState(0);
        order.setName(user.getName());
        order.setTelephone(user.getTelephone());
        order.setUid(user.getUid());
        order.setTotal(product.getShopPrice() * count);
        List<OrderItem> items = new ArrayList<>();
        OrderItem item = new OrderItem();
        item.setItemId(Utils.getUUID());
        item.setCount(count);
        item.setOid(order.getOid());
        item.setSubTotal(order.getTotal());
        item.setProduct(product);
        item.setPid(pid);
        items.add(item);
        order.setOrderItems(items);
        orderService.add(order);
        return order;
    }
}
